import axios from 'axios'
// import qs from 'qs' qs.stringify(data)
import Cookies from 'js-cookie'
import { baseURL, timeout, SUCCESS_CODE, UNAUTH_CODE } from './config'

axios.defaults.timeout = timeout
axios.defaults.baseURL = baseURL
axios.defaults.headers.Authorization = Cookies.get('token')
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.withCredentials = true // axios 默认不发送cookie，需要全局设置true发送cookie

export function setToken(token) {
  axios.defaults.headers.Authorization = token || Cookies.get('token')
}

export function post(url, data) {
  return axios.post(url, data).then((res) => {
    if (res.data.code === SUCCESS_CODE) {
      return Promise.resolve(res.data.data)
    } else if (res.data.code === UNAUTH_CODE) {
      unauth()
    } else {
      return Promise.reject(res.data)
    }
  }).catch((err) => {
    error(err)
    return Promise.reject(err)
  })
}

export function get(url, data) {
  return axios.get(data ? url + param(data) : url).then((res) => {
    if (res.data.code === SUCCESS_CODE) {
      return Promise.resolve(res.data.data)
    } else if (res.data.code === UNAUTH_CODE) {
      unauth()
    } else {
      return Promise.reject(res.data)
    }
  }).catch((err) => {
    error(err)
    return Promise.reject(err)
  })
}

export function postAll(url, data) {
  return axios.post(url, data).then((res) => {
    if (res.data.code === SUCCESS_CODE) {
      return Promise.resolve(res.data)
    } else if (res.data.code === UNAUTH_CODE) {
      unauth()
    } else {
      return Promise.reject(res.data)
    }
  }).catch((err) => {
    error(err)
    return Promise.reject(err)
  })
}

export function getAll(url, data) {
  return axios.get(data ? url + param(data) : url).then((res) => {
    if (res.data.code === SUCCESS_CODE) {
      return Promise.resolve(res.data)
    } else if (res.data.code === UNAUTH_CODE) {
      unauth()
    } else {
      return Promise.reject(res.data)
    }
  }).catch((err) => {
    error(err)
    return Promise.reject(err)
  })
}

function param(data) {
  let str = '?'
  Object.keys(data).forEach((item) => {
    str += item + '=' + data[item] + '&'
  })
  return str.substr(0, str.length - 1)
}
function unauth() {
  console.log('unauth')
  Cookies.remove('token')
  window.location.reload()
}

function error(err) {
  if (err.response && err.response.status === 401) {
    window.vue.reload()
  }
}